const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //生成html
//定义地址
const ROOT_PATH = path.resolve(__dirname);
const APP_PATH = path.resolve(ROOT_PATH, 'src'); //__dirname 中的src目录，以此类推
const BUILD_PATH = path.resolve(ROOT_PATH, '/dist'); //发布文件所存放的目录
const PUBLIC_PATH = '/';
const getEntry = (globPath, pathDir) => {
    let files = glob.sync(globPath);
    let entries = {}, entry, dirname, basename, pathname, extname;
    for (let i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.normalize(path.join(dirname, basename));
        pathDir = path.normalize(pathDir);
        if (pathname.startsWith(pathDir)) {
            pathname = pathname.substring(pathDir.length)
        }
        entries[pathname] = ['./' + entry];
    }
    return entries;
};
const entries = getEntry('src/js/page/**/*.js', 'src/js/page/');
const config = {
    devtool: 'eval',
    entry: entries,
    output: {
        path: BUILD_PATH, //输出目录的配置，模板、样式、脚本、图片等资源的路径配置都相对于它
        publicPath: PUBLIC_PATH,				//模板、样式、脚本、图片等资源对应的server上的路径
        filename: 'js/[name].js',			//每个页面对应的主js的生成配置
        chunkFilename: 'js/[id].chunk.js'   //chunk生成的配置
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /^node_modules$/,
            loader: 'babel',
            include: [APP_PATH]
        }, {
            test: /\.css$/,
            loaders: ['style', 'css', 'postcss']
        }, {
            test: /\.less$/,
            exclude: /^node_modules$/,
            loaders: ['style', 'css', 'postcss', 'less'],
            include: [APP_PATH]
        }, {
            test: /\.scss$/,
            exclude: /^node_modules$/,
            loader: ['style', 'css', 'postcss', 'sass'],
            include: [APP_PATH]
        }, {
            //html模板加载器，可以处理引用的静态资源，默认配置参数attrs=img:src，处理图片的src引用的资源
            test: /\.html$/,
            loader: "html-loader?-minimize&interpolate=require"
        }, {
            test: /\.(eot|woff|svg|ttf|woff2|gif|appcache)(\?|$)/,
            loader: 'file-loader?name=img/[name].[ext]'
        }, {
            test: /\.(png|jpg|gif)$/,
            loader: 'url-loader?limit=8192&name=img/[hash:8].[name].[ext]'
        }]
    },
    externals: {
        jquery: 'window.$'
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('development') //定义编译环境
            }
        }),
        new webpack.HotModuleReplacementPlugin(),// 开启全局的模块热替换（HMR）
    ],
    resolve: {
        extensions: ['', '.js', '.jsx', '.less', '.scss', '.css'], //后缀名自动补全
        // 自定义路径别名
        alias: {
            IMG: path.join(APP_PATH, 'img'),
            STYLE: path.join(APP_PATH, 'css'),
            LIB: path.join(APP_PATH, 'lib'),
            COMPONENT: path.join(APP_PATH, 'js/components'),
            UTIL: path.join(APP_PATH, 'js/utils')
        }
    }
};

const pages = Object.keys(getEntry('src/view/**/*.html', 'src/view/'));
pages.forEach(function (pathname) {
    let conf = {
        filename: pathname + '.html', //生成的html存放路径，相对于path
        template: 'src/view/' + pathname + '.html', //html模板路径
        inject: false, //js插入的位置，true/'head'/'body'/false
        minify: { //压缩HTML文件
            removeComments: true, //移除HTML中的注释
            collapseWhitespace: false //删除空白符与换行符
        }
    };
    if (pathname in config.entry) {
        // conf.favicon = path.resolve(__dirname, 'src/imgs/favicon.ico');
        conf.inject = 'body';
        conf.chunks = ['vendors', pathname];
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});
module.exports = config;